package com.example.amusic.viewmodel

import android.content.Context
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.amusic.TAG
import com.example.amusic.db.SongEntity
import com.example.amusic.service.PlayServiceModule
import com.example.amusic.service.PlayerController
import com.example.amusic.utils.ConnectivityManagerNetworkMonitor
import com.example.amusic.utils.LocalMusicLoader
import com.example.amusic.utils.NetworkMonitor
import com.example.amusic.utils.toMediaItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

sealed class MainIntent {
    data class InitNetWorkMonitor(val context: Context) : MainIntent()
    object RequestPermission : MainIntent()
    object RequestScan : MainIntent()
    object PlayAllSongListener : MainIntent()
    object PlayNextListener : MainIntent()
    object PlayPrevListener : MainIntent()
    data class OnItemClick(val data: SongEntity, val position: Int) : MainIntent()
}

data class MainState(
    val msg: String = "",
    val scanList: List<SongEntity> = emptyList(),
    val isNetWorkOnline: Flow<Boolean> = flowOf(value = false),
)

class MainViewModel : ViewModel() {
//    ui:StateFlow
//    事件:SharedFlow

    private val _mainIntent = MutableSharedFlow<MainIntent>()
    val mainIntent = _mainIntent.asSharedFlow()

    private val _mainState = MutableStateFlow(MainState())
    val mainState: StateFlow<MainState> = _mainState.asStateFlow()

//    private var connectivityManagerNetworkMonitor: ConnectivityManagerNetworkMonitor? = null

    private var localMusicLoader: LocalMusicLoader? = null

    var playerController: PlayerController? = null

    private var initJob: Job? = null

    init {
        localMusicLoader = LocalMusicLoader()
        createAccount()
        listenerSongState()
    }

    private fun listenerSongState() {
//        viewModelScope.launch {
//            MyApp.playerController.currentSong.observeAsState()
//        }
    }

    fun initPlay() {

    }

    fun dispatch(mainIntent: MainIntent) {
        when (mainIntent) {
            MainIntent.RequestPermission -> {}
            MainIntent.RequestScan -> {
                sacnMedia()
            }

            MainIntent.PlayAllSongListener -> {
                playAllSongs()
            }

            MainIntent.PlayNextListener -> {
                playerController?.next()
            }

            MainIntent.PlayPrevListener -> {
                playerController?.prev()
            }

            is MainIntent.OnItemClick -> {
                playIndexSong(mainIntent.data, mainIntent.position)
            }

            is MainIntent.InitNetWorkMonitor -> initNwtWorkMonitor(mainIntent.context)

        }
    }

    private fun playIndexSong(data: SongEntity, index: Int) {
        viewModelScope.launch {
            val songs = mainState.value.scanList.map { it.toMediaItem() }
            playerController?.replaceAll(songs, songs[index])
        }
    }


    private fun initNwtWorkMonitor(context: Context) {
        val connectivityManagerNetworkMonitor: NetworkMonitor =
            ConnectivityManagerNetworkMonitor(context)
        _mainState.value = _mainState.value.copy(
            isNetWorkOnline = connectivityManagerNetworkMonitor.isOnline.map(Boolean::not).stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = false
            )
        )
    }

    /**
     * 扫描本地音乐
     */
    private fun sacnMedia() {
        viewModelScope.launch(Dispatchers.IO) {
            if (localMusicLoader == null) return@launch
            Log.e(TAG, "sacnMedia: 开始进行扫描")
            val songList = localMusicLoader!!.load()
            if (songList.isNotEmpty()) {
                _mainState.value = _mainState.value.copy(scanList = songList)
            } else {
                _mainState.value = _mainState.value.copy(msg = "暂无本地音乐")
            }
        }
    }


    private fun playAllSongs() {
        viewModelScope.launch {
            if (playerController == null) {
                playerController = PlayServiceModule.initPlayController()
            }
            val songs = mainState.value.scanList.map { it.toMediaItem() }
            playerController?.replaceAll(songs, songs.first())
        }
    }

    private fun createAccount() {
//        viewModelScope.launch {
//            val client = Client(MyApp.ctx)
//                .setEndpoint("https://cloud.appwrite.io/v1")
//                .setProject("666adcb00022a8514f8f")
//                .setSelfSigned(true)
//
//            val account = Account(client)
//            val user = account.create(
//                userId = UUID.randomUUID().toString(),
//                email = "test@gmail.com",
//                password = "test123456",
//                name = "test"
//            )
//            Log.e(TAG, "createAccount: user = ${user}")
//        }

    }
}